package work.chenxr.restful.encrypt.advice;

import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;
import work.chenxr.restful.encrypt.annotation.ApiSecurity;

import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;

/**
 * @Author Chenxr
 * @Date 2023/10/28
 * @Description 获取加密请求体
 */
@ControllerAdvice
public class DecryptRequestBodyAdvice implements RequestBodyAdvice {
    @Value("${cipher-security.enable}")
    private boolean enableCipherSecurity;

    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        if (!enableCipherSecurity) {
            return false;
        }

        // 检测注解是否开启解密
        Method method = methodParameter.getMethod();
        if (!ObjectUtils.isEmpty(method)) {
            ApiSecurity apiSecurity = method.getDeclaredAnnotation(ApiSecurity.class);
            if (!ObjectUtils.isEmpty(apiSecurity)) {
                return apiSecurity.decrypt();
            }
        }

        return false;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter,
                                           Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        return new DecryptHttpInputMessage(inputMessage);
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
                                Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }

    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
                                  Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }
}
